<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\Backend;
use think\response\View;
use hg\apidoc\annotation as Apidoc;
use think\facade\Db;

/**
 * 通知公告
 * @Apidoc\Group("base")
 * @package app\admin\controller
 */
class Notice extends Backend
{
    /**
     * 初始化参数
     * @author 贾二小
     * @since 2021/7/3
     */
    public function initialize()
    {
        $this->config = [
            'name'=>'通知公告',
            'table_name'=>'notice',//表名
            'item_table_name'=>'notice_user',//表名
            'user_table_name'=>'user',//表名
            'table_alias' => 'a',//别名
            'table_field'=>'*',//显示默认字段
            'form_field' => 'id,title,content,type,status,public_org_id,public_org_name,public_time,public_user_id,public_user_name,cancel_time',//表单字段，没有设置则默认为显示字段默认是不能有*和.)
            'form_validated1' => [
                'title' => ['msg' => '标题不能为空', 'regex' => false, 'pcre' => '',],
                'type' => ['msg' => '类型不能为空', 'regex' => false, 'pcre' => '',],
                'content' => ['msg' => '内容不能为空', 'regex' => false, 'pcre' => '',],
            ],//表单验证
            'form_validated2' => [],//重复验证
            'search_table'=> null,//关联表时，需要重写
            'is_limit'=> false,//是否分页显示
            'search_field' => 'id,title,type,status,create_user_id,create_date,update_user_id,update_date',//查询表格字段
            'search_param'=>[],//查询表格条件
            'is_delete'=> true,//是否假删除
            'id_validated' => [
                'id' => ['msg' => 'ID不能为空', 'regex' => false, 'pcre' => '',],
            ],//表单验证
        ];
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    /**
     * @Apidoc\Title("获取通知明细")
     * @Apidoc\Desc("获取通知明细")
     * @Apidoc\Url("/admin/notice/detail")
     * @Apidoc\Method("GET")
     * @Apidoc\Tag("测试 基础")
     * @Apidoc\Param("id", type="int",default="0",desc="唯一id" )
     * @author 贾二小
     * @since 2021/7/16
     */
    public function detail(){
        //获取参数
        $id = intval(input('id'));
        //数据验证
        $this->form_validated('id_validated');
        //查询公告明细
        $data = Db::name($this->config['table_name'])
            ->field($this->config['form_field'])
            ->where(['id'=>$id])
            ->find();
        if($data['status'] === 1){
            //通知公告状态为1时，查看更新查看人和时间
            Db::name($this->config['item_table_name'])
                ->where(['user_id'=>_current_user('id'),'notice_id'=>$id])
                ->update(['status'=>1,'read_time'=>datetime()]);
        }
        $readUserData = Db::name($this->config['item_table_name'])
            ->field('user_id,read_time,status as read_status')
            ->where(['notice_id'=>$id])
            ->select()->toArray();
        $data['user_read_list'] = $readUserData;
        $data['user_id_list'] = array_key_value($readUserData, 'user_id');
        //根据ID绑定用户名
        $data['user_read_list'] = user_id_name($data['user_read_list'],[['id'=>'user_id','name'=>'user_name']]);
        //返回
        $this->success($data);
    }

    /**
     * 新增/编辑通知公告
     * @author 贾二小
     * @since 2021/6/27
     */
    public function save(){
        //获取参数
        $id = intval(input('id'));
        $title = input('title');
        $type = input('type');
        $content = input('content');
        $status = intval(input('status'));
        $user_id_list = input('user_id_list/a');
        //数据验证
        $this->form_validated('form_validated1');
        //数据组装
        $data = [];
        $data['title'] = $title;
        $data['type'] = $type;
        $data['content'] = $content;
        $data['status'] = $status;
        if($status === 0 || $status === 1){
            $data = $this->getData($data);
        }

        if($id == 0){
            //新增
            $data['create_user_id'] = _current_user('id');
            //数据库操作
            Db::transaction(function () use ($data, $user_id_list) {
                //增加通知明细
                $notice_id = Db::name($this->config['table_name'])->insertGetId($data);
                //增加通知到的人
                $itemData = [];
                foreach ($user_id_list as $vo){
                    $itemData[] = ['notice_id'=>$notice_id, 'user_id'=>$vo,];
                }
                Db::name($this->config['item_table_name'])->insertAll($itemData);
            });
        }else{
            //编辑
            $data['update_user_id'] = _current_user('id');
            //数据库操作
            Db::transaction(function () use ($id, $data, $user_id_list) {
                //增加通知明细
                Db::name($this->config['table_name'])->where(['id'=>$id])->update($data);
                //增加通知到的人
                $itemData = [];
                foreach ($user_id_list as $vo){
                    $itemData[] = ['notice_id'=>$id, 'user_id'=>$vo,];
                }
                Db::name($this->config['item_table_name'])->where(['notice_id'=>$id])->delete();
                Db::name($this->config['item_table_name'])->insertAll($itemData);
            });
        }
        //返回
        $this->success();
    }

    /**
     * 查看通知公告页面
     * @author 贾二小
     * @since 2021/6/26
     */
    public function detail_page(): View
    {
        return view();
    }

    /**
     *
     * @Apidoc\Title("发布通知公告")
     * @Apidoc\Desc("发布/撤回通知公告")
     * @Apidoc\Url("/admin/notice/change_status")
     * @Apidoc\Method("GET")
     * @Apidoc\Tag("测试 基础")
     * @Apidoc\Param("id", type="int",default="0",desc="唯一id" )
     * @Apidoc\Param("status", type="int",default="0",desc="状态" )
     * @author 贾二小
     * @since 2021/6/26
     */
    public function change_status(){
        //获取参数
        $id = intval(input('id'));
        $status = intval(input('status'));
        //数据验证
        $this->form_validated('id_validated');
        //数据组装
        $data = [];
        $data['status'] = $status;
        $data['update_user_id'] = _current_user('id');
        if($status === 1){
            //发布
            $data = $this->getData($data);
            //日志
            $this->sLog($this->config['name'].'_发布',"成功");
        }elseif ($status === 2){
            //撤回
            $data['cancel_time'] = datetime();
            //日志
            $this->sLog($this->config['name'].'_撤回',"成功");
        }
        //数据库操作
        Db::name($this->config['table_name'])->where(['id'=>$id])->update($data);
        //返回
        $this->success();
    }

    /**
     * 已收公告页面
     * @author 贾二小
     * @since 2021/7/16
     */
    public function received_page(){
        return view();
    }

    /**
     * 已收公告列表
     * @author 贾二小
     * @since 2021/6/27
     */
    public function received(){
        //获取参数
        $type = intval(input('type'));
        $key = input('key');
        //Where条件
        $map = [];
        if(!empty($type)){
            $map[] = ['b.status','=',$type];
        }
        if(!empty($key)){
            $map[] = ['b.title|b.content','like','%'.$key.'%'];
        }
        //获取当前登陆人的公告
        $map[] = ['a.user_id','=',_current_user('id')];
        $map[] = ['b.is_delete','=',0];
        //分页
        $limit = input('limit/d',15);
        $page = input('page/d',1);
        //排序
        $sort = input("sort",'id');
        $order = input("order",'desc');
        //查询数据
        $count = Db::name($this->config['item_table_name'])
            ->alias('a')
            ->join($this->config['table_name'].' b','a.notice_id=b.id','left')
            ->where($map)->count();
        $list = Db::name($this->config['item_table_name'])
            ->alias('a')
            ->join($this->config['table_name'].' b','a.notice_id=b.id','left')
            ->field('b.id,a.status as read_status,a.read_time,b.title,b.content,b.type,b.status,b.public_org_name,b.public_time,b.public_user_name')
            ->where($map)->order($sort,$order)
            ->page($page,$limit)->select();
        //返回数据
        $data = ['data'=>$list, 'count'=>$count];
        $this->success($data, 0);
    }

    private function getData(array $data): array
    {
        $current_user_emp = _current_user('emp');
        $data['public_org_id'] = $current_user_emp['org_id'];
        $data['public_org_name'] = $current_user_emp['org_name'];
        $data['public_user_id'] = _current_user('id');
        $data['public_user_name'] = _current_user('name');
        $data['public_time'] = datetime();
        return $data;
    }
}